package com.h.files.selector.activity.fragment;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.TextView;

import com.h.files.selector.R;
import com.h.files.selector.activity.MultiFileSelectorActivity;
import com.h.files.selector.activity.adapter.NListAdapter;
import com.h.files.selector.activity.listener.OnNScrollListener;
import com.h.files.selector.activity.model.DirctoryModel;
import com.h.files.selector.activity.model.FileModel;
import com.h.files.selector.activity.util.BitmapUtils;
import com.h.files.selector.activity.util.FileUtils;
import com.h.files.selector.activity.util.UiUtils;
import com.squareup.picasso.Callback;
import com.squareup.picasso.RequestCreator;

@SuppressLint("NewApi")
public class FileSelectorFragment extends Fragment {

	private MultiFileSelectorActivity activity;
	private String currPath = null;
	private List<DirctoryModel> dirctoryList = new ArrayList<DirctoryModel>();
	private int maxNum = 9;
	private ListPopupWindow popup;

	private ListView listView;
	private TextView bar;
	private ImageView back;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (200 == msg.what) {
				List<FileModel> data = (List<FileModel>) msg.obj;
				NListAdapter<FileModel> nListAdapter = (NListAdapter<FileModel>) listView.getAdapter();
				nListAdapter.clear();
				nListAdapter.addData(data);
				nListAdapter.updateUI();
			}
		}
	};

	private void readerFiles(final String path) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				File root = null;
				if (null == path) {
					root = Environment.getExternalStorageDirectory();
				} else {
					root = new File(path);
				}
				FileModel file = null;
				List<FileModel> list = new ArrayList<FileModel>();
				File[] childrens = root.listFiles();
				if (null == childrens)
					childrens = new File[] {};
				for (File f : childrens) {
					file = new FileModel();
					file.abstractPath = f.getAbsolutePath();
					file.fileDirctory = f.getParent();
					file.fileName = f.getName();
					file.isDirctory = f.isDirectory();
					if (file.isDirctory) {
						String[] files = f.list();
						file.fileNum = null == files ? 0 : files.length;
					} else {
						file.fileNum = (int) f.length();
					}
					file.parentName = f.getParentFile().getName();
					file.isSelected = activity.getResultList().contains(file.abstractPath);
					list.add(file);
					file = null;
				}
				Collections.sort(list, new Comparator<FileModel>() {
					@Override
					public int compare(FileModel lhs, FileModel rhs) {
						return (rhs.isDirctory + "").compareTo((lhs.isDirctory + ""));
					}
				});
				if (0 == dirctoryList.size()) {
					File[] roots = Environment.getExternalStorageDirectory().listFiles(new FileFilter() {
						@Override
						public boolean accept(File pathname) {
							return pathname.isDirectory();
						}
					});
					DirctoryModel dm = null;
					if (null != roots) {
						for (File f : roots) {
							dm = new DirctoryModel();
							String[] files = f.list();
							dm.files = null == files ? 0 : files.length;
							dm.name = f.getName();
							dm.path = f.getAbsolutePath();
							dirctoryList.add(dm);
							dm = null;
						}
					}
					dm = new DirctoryModel();
					root = Environment.getExternalStorageDirectory();
					String[] files = root.list();
					dm.files = null == files ? 0 : files.length;
					dm.name = root.getAbsolutePath();
					dm.path = root.getAbsolutePath();
					currPath = dm.path;
					dirctoryList.add(0, dm);
				}
				Message msg = handler.obtainMessage(200, list);
				handler.sendMessage(msg);
			}
		}).start();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.f_multi_file_selector, container, false);
		initWidget(view);
		initListener();
		initData();
		return view;
	}

	private void initWidget(View view) {
		listView = (ListView)view.findViewById(R.id.f_multi_file_listView);
		bar = (TextView)view.findViewById(R.id.f_multi_file_dir);
		back = (ImageView)view.findViewById(R.id.i_multi_file_back);

		listView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		listView.setAdapter(new NListAdapter<FileModel>(R.layout.i_file_selector, this.getActivity()) {
			@SuppressLint({ "ResourceAsColor", "NewApi" })
			@Override
			public void bindData(int position, View convertView, ViewGroup parent, final FileModel t) {
				ImageView imageView = (ImageView) getView(R.id.i_file_type);
				convertView.setBackgroundColor(android.R.color.holo_red_light);
				setText(R.id.i_file_name, t.fileName);
				if (t.isDirctory)
					setText(R.id.i_file_datetime, "总数：" + t.fileNum);
				else
					setText(R.id.i_file_datetime, "大小：" + FileUtils.formatFileSize(t.fileNum));
				RequestCreator rc = null;
				if (t.isDirctory) {
					rc = BitmapUtils.getPicasso().load(R.drawable.default_folder);
				} else {
					if (t.fileName.endsWith("jpg") || t.fileName.endsWith("png") || t.fileName.endsWith("jpeg") || t.fileName.endsWith("webmp") || t.fileName.endsWith("ico")) {
						rc = BitmapUtils.getPicasso().load(new File(t.abstractPath)).error(R.drawable.default_image);
					} else if (t.fileName.endsWith("gif")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_gif);
					} else if (t.fileName.endsWith("doc")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_doc);
					} else if (t.fileName.endsWith("xls")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_xls);
					} else if (t.fileName.endsWith("txt")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_txt);
					} else if (t.fileName.endsWith("log")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_log);
					} else if (t.fileName.endsWith("html")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_html);
					} else if (t.fileName.endsWith("mp3")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_mp3);
					} else if (t.fileName.endsWith("mp4")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_mp4);
					} else if (t.fileName.endsWith("pdf")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_pdf);
					} else if (t.fileName.endsWith("apk")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_apk);
					} else if (t.fileName.endsWith("zip") || t.fileName.endsWith("rar")) {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_zip);
					} else {
						rc = BitmapUtils.getPicasso().load(R.drawable.default_unknow);
					}
				}
				rc.resize(70, 70).centerCrop().config(Config.ARGB_8888).into(imageView, new Callback() {
					@Override
					public void onError() {
						t.isLoadFail = true;
					}

					@Override
					public void onSuccess() {
						t.isLoadFail = false;
					}
				});
				getView(R.id.i_file_selected).setVisibility(t.isSelected ? View.VISIBLE : View.GONE);
			}
		});

	}

	private void initListener() {
		listView.setOnScrollListener(new OnNScrollListener(listView));
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				NListAdapter<FileModel> adapter = (NListAdapter<FileModel>) listView.getAdapter();
				FileModel fileModel = adapter.getItem(position);
				if (fileModel.isDirctory) {
					changeDirctory(new File(fileModel.abstractPath));
					return;
				}
				if (!activity.getResultList().contains(fileModel.abstractPath)) {
					if (activity.getResultList().size() >= maxNum) {
						UiUtils.showLong(activity, "已达到最大数量...");
						return;
					}
					fileModel.isSelected = true;
					activity.getResultList().add(fileModel.abstractPath);
				} else {
					fileModel.isSelected = false;
					activity.getResultList().remove(fileModel.abstractPath);
				}
				NListAdapter.updateUI(listView, position);
				activity.setSelectedNum(activity.getResultList().size());
			}
		});
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				File f = new File(currPath);
				changeDirctory(f.getParentFile());
			}
		});
		bar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (null != popup && popup.isShowing()) {
					popup.dismiss();
					popup = null;
				} else {
					popup = new ListPopupWindow(activity);
					popup.setModal(true);
					popup.setAnchorView(v);
					popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
					popup.setAdapter(new NListAdapter<DirctoryModel>(R.layout.i_dirctory, activity, dirctoryList) {
						@Override
						public void bindData(int position, View convertView, ViewGroup parent, DirctoryModel t) {
							ImageView iv = (ImageView) getView(R.id.i_folder);
							BitmapUtils.getPicasso().load(R.drawable.default_folder).placeholder(R.drawable.default_folder).resize(55, 55).centerCrop().into(iv);
							setText(R.id.i_dirctory_name, t.name);
							setText(R.id.i_dirctory_list, "总数：" + t.files);
							getView(R.id.i_dirctory_selected).setVisibility(t.isSelected ? View.VISIBLE : View.GONE);
						}
					});
					popup.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							NListAdapter<DirctoryModel> adapter = ((NListAdapter<DirctoryModel>) parent.getAdapter());
							DirctoryModel dm = adapter.getItem(position);
							popup.getListView().setSelection(position);
							changeDirctory(new File(dm.path));
							popup.dismiss();
						}
					});
					popup.setWidth(UiUtils.getScreenWidth(activity));
					popup.setHeight((UiUtils.getScreenHeight(activity) / 11) * 5);
					popup.show();
				}
			}
		});
	}

	private void changeDirctory(File dir) {
		if (dir.getAbsolutePath().length() >= Environment.getExternalStorageDirectory().getAbsolutePath().length()) {
			for (DirctoryModel dm : dirctoryList) {
				dm.isSelected = dm.path.equals(dir.getAbsolutePath());
			}
			currPath = dir.getAbsolutePath();
			String showName = dir.getName();
			if (dir.getAbsolutePath().length() == Environment.getExternalStorageDirectory().getAbsolutePath().length()) {
				showName = dir.getAbsolutePath();
			}
			bar.setText(showName);
			readerFiles(dir.getAbsolutePath());
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = (MultiFileSelectorActivity) activity;
		this.maxNum = this.activity.getIntent_request_key_max_num();
	}

	private void initData() {
		readerFiles(null);
	}
}
